/**
 * Author: ligj@mapbar.com
 * Create Time: 2017/12/15 15:15
 * Description: 拦截器配置
 */

import axios from 'axios';
import Vue from 'vue';
import Qs from 'qs';
import Interceptors from './interceptors';

let ajaxConfig = {
    baseURL: '',
    timeout: 600000,
    withCredentials: false,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
};

const resultProcessor = function (result = {}) {
    let rdata = result.data;
    let token = window.localStorage.getItem('token')
    if (rdata.code === 200) {
        return Promise.resolve(rdata.data || rdata.result);
    } else if (rdata.code === 501 && (!token || token === '')) {
        return
    } else if (rdata.code === 401) { // token失效，返回登陆
        Vue.eventEmitter.emit('log_out');
    } else {
        if(rdata.code === "20107"){
            rdata.message = "登陆超时";
            window.localStorage.clear();
            setTimeout(function () {
                Vue.eventEmitter.emit('user_invalid');
            })
        }
        rdata.message = rdata.message || rdata.msg || '服务器错误';
        return Promise.reject(rdata);
    }
};

const req = function (ajax, method, url, rawData = {}, processor, isUpload = false) {
    //let data = {...rawData};
    let data = rawData
    // 去掉参数空格
    try{
        if(data.constructor === Object){
            Object.keys(data).map(item => {
                if(data[item] && data[item].constructor === String){
                    data[item] = data[item].trim();
                }
            })
        }
    }catch (e){
        data = {...rawData};
    }

    url = /^(http|https):\/\//.test(url) ? url : (ajax.defaults.baseURL + url);
    let options = {
        url,
        method
    };

    if (data && typeof data === 'object') {
        for (let _d in data) {
            // get请求时去掉空值
            if (method === 'get' && (data[_d] === '' || data[_d] === undefined || data[_d] === null || data[_d] === 'null')) {
                delete data[_d];
            }
        }
    }
    if (method === 'get') {
        options.params = data;
        // data['__rid'] = Math.random();
        options.paramsSerializer = function (params) {
            return Qs.stringify(params);
        };
    } else if (method === 'post') {
        if (data instanceof FormData) {
            options.data = data;
        } else if (isUpload) {
            let formData = new FormData();
            Object.keys(data).map((key) => {
                formData.append(key, data[key])
            });
            options.data = formData;
            options.headers = {...ajax.headers};
            options.headers['Content-Type'] = undefined;

        } else {
            options.data = JSON.stringify(data)
        }
    }

    processor = processor || resultProcessor;

    return ajax.request(options).then(function (res) {
        return processor(res);
    }, function (err) {
        return processor(err.response);
    });
};

let Request = function (reqConfig) {
    let ajax = null;

    const getAjax = function (isUpload) {
        if (!ajax) {
            ajax = axios.create({...ajaxConfig, ...reqConfig});
            ajax.interceptors.request.use(Interceptors.request, Interceptors.requestError);
            ajax.interceptors.response.use(Interceptors.response, Interceptors.responseError);
        }
        return ajax;
    };

    return {
        post: (url, data, processor, isUpload = false) => {
            if (typeof data === 'function' && arguments.length === 2) {
                processor = data;
                data = null;
            }
            return req(getAjax(isUpload), 'post', url, data, processor, isUpload);
        },
        get: (url, data, processor) => {
            if (arguments.length === 2 && typeof data === 'function') {
                processor = data;
                data = null;
            }
            return req(getAjax(), 'get', url, data, processor);
        },
        makeUrl: function (path = '', params) {
            if(params){
                return ajax.defaults.baseURL + path + '?' + Qs.stringify(params);
            }else {
                return ajax.defaults.baseURL + path;
            }

        }
    };
};

const  _request = Request();
export default {
    ..._request,
    create: Request,
    config(opts) {
        ajaxConfig = {
            ...ajaxConfig,
            ...opts
        }
    }
};
